package com.jiangjiang.eshop.order.price.v1.calculator.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiangjiang.eshop.commodity.dto.GoodsSkuDTO;
import com.jiangjiang.eshop.commodity.service.CommodityService;
import com.jiangjiang.eshop.order.dto.OrderItemDTO;
import com.jiangjiang.eshop.order.dto.PromotionActivityResult;
import com.jiangjiang.eshop.order.price.v1.calculator.AbstractGiftPromotionActivityCalculator;
import com.jiangjiang.eshop.order.price.v1.calculator.PromotionActivityCalculator;
import com.jiangjiang.eshop.promotion.dto.PromotionActivityDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.xml.transform.Result;
import java.util.List;

/**
 * @Author Jianghaowen
 * @Date 2021/7/14
 * @Description: 满赠类型的促销胡活动的处理器
 * @Version V1.0
 **/
@Component
public class ReachGiftPromotionActivityCalculator extends AbstractGiftPromotionActivityCalculator implements PromotionActivityCalculator {

    @Autowired
    private CommodityService commodityService;
    /**
     *
     * @param item 订单条目
     * @param promotionActivity 促销活动
     * @return
     * @throws Exception
     */
    @Override
    public PromotionActivityResult calculate(OrderItemDTO item, PromotionActivityDTO promotionActivity) throws Exception {
        Double totalPrice = item.getPurchasePrice() * item.getPurchaseQuantity();
        //{“thresholdAmount”: 550,“giftGoodsSkuIds”: [2, 340, 590]}
        String rulesJson = promotionActivity.getRule();
        JSONArray rules = JSONArray.parseArray(rulesJson);
        PromotionActivityResult result = new PromotionActivityResult();
        for (int i = 0; i < rules.size(); i++) {
            JSONObject jsonObject = rules.getJSONObject(i);
            Double thresholdAmount = jsonObject.getDouble("thresholdAmount");

            if (totalPrice >= thresholdAmount) {
                List<Long> giftGoodsSkuIds = JSONObject.parseArray(jsonObject.getString("giftGoodsSkuIds"), Long.class);
                List<GoodsSkuDTO> goodsSkuByIds = commodityService.getGoodsSkuByIds(giftGoodsSkuIds);
                result.setOrderItems(createGiftOrderItems(goodsSkuByIds));
            }

        }

        return null;

    }

}
